package com.asiainfo.indb.control.db.pool;

import com.asiainfo.indb.model.InDbGather;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取连接池
 *
 * @author zym
 * @date 2019-10-18 14:49
 */
public class DbPoolFactory {

    private static final Map<String, IDbPool> POOL_MAP = new ConcurrentHashMap<>();

    /**
     * 获取连接池
     *
     * @param dbData 数据库数据
     * @return 连接池
     */
    public static IDbPool getPool(InDbGather dbData) {
        int keySize = 4;
        if (dbData != null && dbData.size() >= keySize) {
            String key = generateKey(dbData);

            IDbPool pool;
            synchronized (POOL_MAP) {
                pool = POOL_MAP.computeIfAbsent(key, k -> initPool(dbData));
            }

            return pool;
        }

        return null;
    }

    /**
     * @param dbData 表数据
     * @return 池
     */
    private static IDbPool initPool(InDbGather dbData) {
        return new JdbcPool().init(dbData);
    }

    private static String generateKey(InDbGather dbData) {
        String type = dbData.get("DB_TYPE"),
                url = dbData.get("DB_URL"),
                user = dbData.get("DB_USER"),
                password = dbData.get("DB_PASSWORD");
        return type + ":" + url + ":" + user + ":" + password;
    }

}
